package com.irdstudio.devops.console.util;

import ch.ethz.ssh2.*;
import com.irdstudio.sdk.beans.ssh.utils.RemoteShellClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * @author lwc
 * @Description TODO
 * @createTime 2020年12月15日
 */
public class MyRemoteShellClient {
    private static Logger logger = LoggerFactory.getLogger(RemoteShellClient.class);
    private String ip;
    private String user;
    private String passwd;
    private Connection conn;

    public MyRemoteShellClient(String ip, String user, String passwd) {
        this.ip = ip;
        this.user = user;
        this.passwd = passwd;
    }

    public boolean login() {
        logger.error("用户{}密码{}登录Linux服务器{}......", new Object[]{this.user, this.passwd, this.ip});
        this.conn = new Connection(this.ip);

        try {
            this.conn.connect();
            return this.conn.authenticateWithPassword(this.user, this.passwd);
        } catch (IOException var2) {
            logger.error("登录远程Linux服务器失败！", var2);
            return false;
        }
    }

    public void putFile(String fileName, String remotePath) {
        logger.info("服务器:{},上传文件：{}到{}", new Object[]{this.ip, fileName, remotePath});
        SCPClient sc = new SCPClient(this.conn);

        try {
            sc.put(fileName, remotePath);
        } catch (IOException var5) {
            logger.error("上传本地文件到服务器目录下出现异常！", var5);
        }

    }

    public boolean copyFile(String fileName, String localPath) {
        logger.info("服务器:{},下载文件：{}到本地{}", new Object[]{this.ip, fileName, localPath});
        SCPClient sc = new SCPClient(this.conn);

        try {
            sc.get(fileName, localPath);
            logger.info("下载完成");
        } catch (IOException var5) {
            logger.error("下载服务器文件到本地目录出现异常！", var5);
            return false;
        }
        return true;

    }

    public ArrayList<String> getFileProperties(String remotePath) {
        ArrayList<String> files= new ArrayList<>();
        try {
            SFTPv3Client sft = new SFTPv3Client(this.conn);
            Vector<?> v = sft.ls(remotePath);
            for(int i = 0; i < v.size(); ++i) {
                new SFTPv3DirectoryEntry();
                SFTPv3DirectoryEntry s = (SFTPv3DirectoryEntry)v.get(i);
                String fileName = s.filename;
                if (!".".equals(fileName)&&!"..".equals(fileName)){
                    files.add(fileName);
                }
                Long fileSize = s.attributes.size;
                logger.info("文件名:{},文件大小:{}", fileName, fileSize);
            }

            sft.close();
        } catch (SFTPException var8) {
            logger.error("在远程LINUX服务器上，在指定目录下，获取文件各个属性出现异常！", var8);
            if (var8.getMessage().contains("No such file")) {
                return files;
            }
        } catch (Exception var9) {
            logger.error("在远程LINUX服务器上，在指定目录下，获取文件各个属性出现异常！", var9);
        }

        return files;
    }
    public boolean getFileProperties2(String remotePath) {
        try {
            SFTPv3Client sft = new SFTPv3Client(this.conn);
            Vector<?> v = sft.ls(remotePath);

            for(int i = 0; i < v.size(); ++i) {
                new SFTPv3DirectoryEntry();
                SFTPv3DirectoryEntry s = (SFTPv3DirectoryEntry)v.get(i);
                String fileName = s.filename;
                Long fileSize = s.attributes.size;
                logger.info("文件名:{},文件大小:{}", fileName, fileSize);
            }
            sft.close();
        } catch (SFTPException var8) {
            logger.error("在远程LINUX服务器上，在指定目录下，获取文件各个属性出现异常！", var8);
            if (var8.getMessage().contains("No such file")) {
                return false;
            }
        } catch (Exception var9) {
            logger.error("在远程LINUX服务器上，在指定目录下，获取文件各个属性出现异常！", var9);
        }

        return true;
    }

    public void delFile(String remotePath, String fileName) {
        try {
            SFTPv3Client sft = new SFTPv3Client(this.conn);
            Vector<?> v = sft.ls(remotePath);

            for(int i = 0; i < v.size(); ++i) {
                new SFTPv3DirectoryEntry();
                SFTPv3DirectoryEntry s = (SFTPv3DirectoryEntry)v.get(i);
                if (s.filename.equals(fileName)) {
                    sft.rm(remotePath + s.filename);
                }

                sft.close();
            }
        } catch (Exception var7) {
            var7.printStackTrace();
        }

    }

    public int exec(String cmds) {
        Integer ret = -1;

        try {
            Session session = this.conn.openSession();
            session.execCommand(cmds);
            logger.info("服务器:{},执行命令：{}", this.ip, cmds);
            this.processStdout(session.getStdout(), "UTF-8");
            session.waitForCondition(32, 3600000L);
            ret = session.getExitStatus();
            session.close();
        } catch (Exception var4) {
            logger.error("执行脚本出现异常！", var4);
        }

        return ret == null ? 1 : ret;
    }

    public String execAndGetStdout(String cmds) {
        String stdout = null;

        try {
            Session session = this.conn.openSession();
            logger.info("服务器:{},执行命令：{}", this.ip, cmds);
            session.execCommand(cmds);
            stdout = this.processStdout2(session.getStdout(), "UTF-8");
            session.waitForCondition(32, 3600000L);
            int ret = session.getExitStatus();
            logger.info("指令执行结束后的状态为：{}", ret);
            session.close();
        } catch (Exception var5) {
            logger.error("执行脚本出现异常！", var5);
        }

        return stdout;
    }

    public void exit() {
        this.conn.close();
    }

    private String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();

        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;

            while((line = br.readLine()) != null) {
                buffer.append(line + "\n");
                System.out.println(line);
                logger.info(line);
            }
            System.out.println(buffer);

            br.close();
        } catch (UnsupportedEncodingException var7) {
            logger.error("解析脚本出错！", var7);
        } catch (IOException var8) {
            logger.error("解析脚本出错！", var8);
        }

        return buffer.toString();
    }
    private String processStdout2(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();

        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;

            while((line = br.readLine()) != null) {
                if (!"".equals(line)) {
                    buffer.append(line).append("\n");
                }
            }

            br.close();
        } catch (UnsupportedEncodingException var7) {
            logger.error("解析脚本出错！", var7);
        } catch (IOException var8) {
            logger.error("解析脚本出错！", var8);
        }

        return buffer.toString();
    }
}
